﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using SmoLiteApi.Sql;
using System.Data.SqlClient;
using SmoLiteApi.Helper;

namespace SmoLiteApi
{
    /// <summary/>
    public class SchemaExtendedPropertyCollection : IEnumerable<SchemaExtendedProperty>
    {
        private Schema _schema;

        /// <summary/>
        internal SchemaExtendedPropertyCollection(Schema schema)
        {
            this._schema = schema;
        }

        /// <summary/>
        public SchemaExtendedProperty this[string name]
        {
            get
            {
                // get the list
                List<SchemaExtendedProperty> extendedProperties = this.FetchObjects(name);

                // return the data
                if (extendedProperties.Count == 0)
                {
                    return null;
                }

                // return the one and only
                return extendedProperties[0];
            }
        }

        /// <summary/>
        public IEnumerator<SchemaExtendedProperty> GetEnumerator()
        {
            return this.FetchObjects(null).GetEnumerator();
        }

        /// <summary/>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.FetchObjects(null).GetEnumerator();
        }

        /// <summary/>
        private List<SchemaExtendedProperty> FetchObjects(string name)
        {
            List<SchemaExtendedProperty> extendedProperties = new List<SchemaExtendedProperty>();

            SchemaExtendedPropertySelectSql schemaExtendedPropertySelectSql = new SchemaExtendedPropertySelectSql();

            // set attributes
            schemaExtendedPropertySelectSql.AddObject(new { Schema = this._schema.Name });
            schemaExtendedPropertySelectSql.AddObject(new { Name = name });

            using (SqlCommandHelper sqlCommandHelper = SqlCommandHelper.FetchSqlCommand(this._schema.Parent.SqlConnection, schemaExtendedPropertySelectSql.Render()))
            {
                using (SqlDataReader sqlDataReader = sqlCommandHelper.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        SchemaExtendedProperty schemaExtendedProperty = new SchemaExtendedProperty(
                            this._schema,
                            sqlDataReader.GetString(sqlDataReader.GetOrdinal(Constant.PARAMETER_NAME)));

                        // set attributes
                        schemaExtendedProperty.Value = sqlDataReader.GetString(sqlDataReader.GetOrdinal(Constant.PARAMETER_VALUE));

                        // add to the list
                        extendedProperties.Add(schemaExtendedProperty);
                    }
                }
            }

            // retun the list
            return extendedProperties;
        }
    }
}
